package com.work.studio.utils;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;

import java.util.ArrayList;
import java.util.List;

public class GsonUtil {
    private static Gson mGson = new Gson();

    private GsonUtil() {
    }

    /**
     * 将json字符串转化成实体对象
     */
    public static <T> T stringToObject(String jsonString, Class<T> cls) throws JsonSyntaxException {
        if (TextUtils.isEmpty(jsonString)) {
            return null;
        } else {
            return mGson.fromJson(jsonString, cls);
        }
    }

    /**
     * 将对象转换为json字符串 或者 把list 转化成json
     */
    public static <T> String objectToString(T object) {
        if (object == null) {
            return null;
        } else {
            return mGson.toJson(object);
        }
    }

    /**
     * 把json 字符串转化成list
     */
    public static <T> List<T> stringToListObject(String json, Class<T> cls) {
        if (TextUtils.isEmpty(json)) {
            return new ArrayList<>();
        }
        Gson gson = new Gson();
        List<T> list = new ArrayList<T>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (final JsonElement elem : array) {
            list.add(gson.fromJson(elem, cls));
        }
        return list;
    }
}
